package io.itit.ecp.admin.server.service.impl;

import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.server.entity.CarbonEmissionPlanDetailEntity;
import io.itit.ecp.admin.server.entity.CarbonEmissionPlanEntity;
import io.itit.ecp.admin.server.entity.extend.CarbonEmissionPlanExtEntity;
import io.itit.ecp.admin.server.mapper.CarbonEmissionPlanMapper;
import io.itit.ecp.admin.server.service.ICarbonEmissionPlanDataService;
import io.itit.ecp.admin.server.service.ICarbonEmissionPlanDetailService;
import io.itit.ecp.admin.server.service.ICarbonEmissionPlanService;
import io.itit.ecp.admin.server.service.ICarbonEmissionUnplanService;
import io.itit.grass.common.server.utils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：碳排放规划配置服务实现类
 * @Date：Create by 2024-01-11 16:45:38
 */
@Service
public class CarbonEmissionPlanServiceImpl extends JoinServiceImpl<CarbonEmissionPlanMapper, CarbonEmissionPlanEntity> implements ICarbonEmissionPlanService {

    @Resource
    private ICarbonEmissionPlanDetailService carbonEmissionPlanDetailService;
    @Resource
    private ICarbonEmissionPlanDataService carbonEmissionPlanDataService;
    @Resource
    private ICarbonEmissionUnplanService carbonEmissionUnplanService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(CarbonEmissionPlanEntity planEntity, List<CarbonEmissionPlanDetailEntity> planDetailList) {
        CarbonEmissionPlanEntity entity = null;
        if(StringUtils.isNotEmpty(planEntity.getId())){
            entity = getById(planEntity.getId());
        }
        // 保存规划配置信息
        boolean save = this.saveOrUpdate(planEntity);
        planDetailList.forEach(x -> x.setCarbonEmissionPlanId(planEntity.getId()));
        // 保存规划配置详情信息
        carbonEmissionPlanDetailService.saveOrUpdateBatch(planDetailList);
        CarbonEmissionPlanExtEntity extEntity = ConvertUtils.convert(planEntity, CarbonEmissionPlanExtEntity.class);
        extEntity.setPlanDetailList(planDetailList);
        if(entity != null){
            // 先删除规划数据，然后插入
            carbonEmissionPlanDataService.delete(entity);
        }
        // 保存规划数据信息
        carbonEmissionPlanDataService.saveData(extEntity);
        // 插入未配置规划数据
        carbonEmissionUnplanService.buildData(planEntity);
        return save;
    }
}